package com.wuster.exception;

import com.wuster.result.Result;
import com.wuster.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * ClassName: GlobalExceptionHandler
 * Package: com.atguigu.lease.common.exception
 * Description: 全局异常处理器
 * @Author VictoriaZhou
 * @Create 2024/7/2 15:40
 * @Version 1.0
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

//    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String handle(Exception e){
        e.printStackTrace();
        return "Result.fail()";
    }


    // 自定义商品异常处理
    @ExceptionHandler(ProductException.class)
    @ResponseBody
    public Result handleProductException(ProductException ex) {
        String error = ex.getMessage();
        int code = ex.getCode();
        // 返回一个响应实体，状态码可以根据需要调整
        return Result.error(code, error);
    }



    // ================================================================================================
    // 捕获共同的异常
    // 1.请求参数类型异常
//    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
//    @ResponseBody
//    public Result handleArgumentTypeMismatchException(MethodArgumentTypeMismatchException ex){
//        String message = String.format("请求参数 '%s' 的值 '%s' 无法转换为所需的类型 '%s'",
//                ex.getName(), ex.getValue(), ex.getRequiredType().getSimpleName());
//        return Result.error(ResultCodeEnum.REQUEST_PARAMETER_TYPE_INCORRECT.getCode(), message);
//    }

    // 2.参数转换异常(添加商品和修改商品)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public Result handleHttpMessageNotReadableException(HttpMessageNotReadableException ex){
        // 通过正则表达式提取字段名
        Pattern pattern = Pattern.compile("\\[\"(.*?)\"]");
        Matcher matcher = pattern.matcher(ex.getMessage());
        String fieldName = null;
        if (matcher.find()) {
            fieldName = matcher.group(1); // 获取匹配到的字段名
        }

        String message = "请求的 JSON 格式错误";
        if (fieldName != null) {
            message = String.format("'%s' 的格式不正确或类型不匹配。", fieldName);
        }

        return Result.error(592, message);
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseBody
    public Result handleMissingParams(NoHandlerFoundException ex) {
        return Result.error(593, "请求参数为空或请求资源：" + ex.getRequestURL() + "不存在");
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseBody
    public Result handleMissingServletRequestParameterException(MissingServletRequestParameterException ex) {
        log.info("捕捉到的参数名是{}",ex.getParameterName());
        return Result.error(593, "请求参数为空或请求资源：" + ex.getParameterName() + "不存在");
    }

    @ExceptionHandler(MultipartException.class)
    @ResponseBody
    public Result handleMultipartException(MultipartException ex) {
        log.info("捕捉到的MultipartException异常: {}", ex.getMessage());
        return Result.error(594, "请求不是multipart类型或文件部分缺失: " + ex.getMessage());
    }

    @ExceptionHandler(MissingServletRequestPartException.class)
    @ResponseBody
    public Result handleMissingServletRequestPartException(MissingServletRequestPartException ex) {
        log.info("捕捉到的缺失文件部分是{}", ex.getRequestPartName());
        return Result.error(594, "请求文件部分缺失或请求资源：" + ex.getRequestPartName() + "不存在");
    }
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseBody
    public Result handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException ex) {
        log.info("捕捉到的参数类型不匹配异常: {}", ex.getMessage());
        return Result.error(591, "请求参数类型不匹配: " + ex.getName() + " 应为 " + ex.getRequiredType().getSimpleName());
    }
    //分类异常处理
    @ExceptionHandler(CategoryException.class)
    @ResponseBody
    public Result handleCategoryException(CategoryException e){
        e.printStackTrace();
        return Result.error(e.getCode(),e.getMessage());
    }

    //管理员功能异常处理
    @ExceptionHandler(AdminException.class)
    @ResponseBody
    public Result handleAdminException(AdminException e){
        e.printStackTrace();
        return Result.error(e.getCode(),e.getMessage());
    }

    //订单异常处理
    @ExceptionHandler(OrderException.class)
    @ResponseBody
    public Result handleOrderException(OrderException e){
        e.printStackTrace();
        return Result.error(e.getCode(),e.getMessage());
    }
}
